/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package projetCalendar.controllers;

import java.io.*;

import java.util.Calendar;
import java.util.Date;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.*;
import javax.servlet.http.*;
import java.text.SimpleDateFormat;
import java.util.List;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import projetCalendar.Model.Evenement;


public class SemaineController extends HttpServlet {
    private EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProjetCalendarPU");
    private EntityManager manager = emf.createEntityManager();
    private EntityTransaction utx;
   
    /** 
    * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
    * @param request servlet request
    * @param response servlet response
    */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        SimpleDateFormat formatDateImport = new SimpleDateFormat("yyyy-MM-dd");
        String date_str = request.getParameter("dateJour");
        Date date = null;
        Date dateMonday = null;
        try { date = formatDateImport.parse(date_str); } catch(Exception e) { }
              
        if(date == null) {
            Calendar date_today = Calendar.getInstance();
            date_today.set(Calendar.SECOND, 0);
            date_today.set(Calendar.MILLISECOND, 0);
            date = date_today.getTime();
            dateMonday = rechercheDebutSemaine(date);
        }
        else{
             dateMonday = rechercheDebutSemaine(date);
        }
        
        
        Query q = manager.createNativeQuery("SELECT * FROM evenements WHERE DATE(date_debut) = ?", Evenement.class);
        Calendar dayWeek = Calendar.getInstance();
        dayWeek.setTime(dateMonday);
        q.setParameter(1, formatDateImport.format(dateMonday));
        List<Evenement> evenements = q.getResultList();
        dayWeek.add(Calendar.DAY_OF_WEEK, +1);
        for(int i =0; i<6; i++){
              List<Evenement> evenementsTmp = null;
              q.setParameter(1, formatDateImport.format(dayWeek.getTime()));
              evenementsTmp = q.getResultList();
              for(int j=0;j<evenementsTmp.size();j++){
                  evenements.add(evenementsTmp.get(j));
              }
              dayWeek.add(Calendar.DAY_OF_WEEK, +1);
        }
        //q.setParameter(1, formatDateImport.format(dateMonday));
        //List<Evenement> evenements = q.getResultList();
        
        request.setAttribute("dateJour", date);
        request.setAttribute("datesemaine", dateMonday);
        request.setAttribute("evenements", evenements);
        
        if(isAjax(request)) {
            getServletContext().getRequestDispatcher("/WEB-INF/vues/Semaine.jsp").forward(request, response);
        } else {
            request.setAttribute("vuePartielle", "/WEB-INF/vues/Semaine.jsp");
            getServletContext().getRequestDispatcher("/WEB-INF/vues/Layout.jsp").forward(request, response);
        }
    } 

    protected Date rechercheDebutSemaine(Date date){
      //  Date dateTrouvé = null;
        Calendar firstDay = Calendar.getInstance();
        firstDay.setTime(date); // date c'est la date récup en param
       // firstDay.setFirstDayOfWeek(Calendar.MONDAY);
       for(;firstDay.get(Calendar.DAY_OF_WEEK)!=firstDay.getFirstDayOfWeek();firstDay.add(Calendar.DAY_OF_WEEK, -1));

        return firstDay.getTime();
    }
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
    * Handles the HTTP <code>GET</code> method.
    * @param request servlet request
    * @param response servlet response
    */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 
    
    protected boolean isAjax(HttpServletRequest request) {
        return request.getHeader("X-Requested-With") != null;
    }
    
    @Override public void destroy() {
        emf.close();
    }
    
    /** 
    * Handles the HTTP <code>POST</code> method.
    * @param request servlet request
    * @param response servlet response
    */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
    * Returns a short description of the servlet.
    */
    public String getServletInfo() {
        return "Short description";
    }
    // </editor-fold>
}
